<template>
  <div>
    <headerXX :name="title"></headerXX>
    <van-tree-select
      :main-active-index="activeIndex"
      height="calc(var(--real-vh, 1vh) * 100 - 55px - env(safe-area-inset-bottom) - env(safe-area-inset-top))"
      :items="items"
      :active-id="activeId"
      @click-nav="onClickNav"
    >
      <template #content>
        <van-pull-refresh
          class="pull-refresh"
          v-model="refreshing"
          @refresh="onRefresh"
        >
          <van-empty
            v-if="list.length == 0 && !error"
            image="search"
            description="未找到数据"
          />
          <van-empty v-if="error" image="error" description="网络错误" />
          <van-list
            :immediate-check="false"
            v-model:loading="loading"
            :finished="finished"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <!-- 列表内容 -->
            <div class="ullist">
              <div class="ul" v-for="(item, index) in list" :key="index">
                <div class="li">
                  <div class="li_img">
                    <van-image
                      class="img"
                      radius="4"
                      width="70"
                      height="70"
                      :src="item.goodImage"
                      mode=""
                    >
                    </van-image>
                  </div>
                  <div class="li_text">
                    <div class="title WZ_size_14" style="font-weight: 700">
                      {{ item.goodName }}
                    </div>
                    <div class="text_JJ WZ_size_10 example1">
                      {{ item.goodDescription }}
                    </div>

                    <div class="li_D">
                      <!-- <div class="Price WZ_size_10" style="color: #027571">
                      {{ item.goodPriceShow }}
                    </div> -->
                      <div
                        class="Price WZ_size_10"
                        :style="
                          item.goodRemainQty > 0
                            ? 'color:#027571'
                            : 'color:#ff9900'
                        "
                      >
                        {{ item.goodRemainQty > 0 ? "有库存" : "暂无库存" }}
                      </div>
                      <div
                        v-if="item.goodRemainQty > 0"
                        class="li_btn"
                        @click="itemClick(item)"
                      >
                        领 取
                      </div>
                    </div>
                  </div>
                </div>
                <van-divider
                  :style="{
                    borderColor: '#999',
                    margin: '5px 0',
                  }"
                >
                </van-divider>
              </div>
            </div>
            <template #error>
              <div class="error-tip" @click="retryLoad">
                <van-icon name="warning" />
                <span>加载失败，点击重试</span>
              </div>
            </template>
          </van-list>
        </van-pull-refresh>
      </template>
    </van-tree-select>
    <van-dialog
      title="共享药房"
      v-model="imgshow"
      @cancel="imgshow = false"
      @confirm="LQ"
      show-cancel-button
    >
      <div style="text-align: center">
        <van-image
          width="150px"
          height="150px"
          :src="SPxx.goodImage"
        ></van-image>
        <div class="WZ_size_16" style="color: #027571">{{ SPxx.goodName }}</div>
        <div class="WZ_size_14" style="padding: 10px 0">
          单人单次可领取一剂本药品，是否确认领取？
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import moment from "moment";
import {
  getSiteCategoryList,
  getMedicineList,
} from "@/api/realAssets/icsharedstation/GXYF/index.js";
import { Toast } from "vant";
import headerXX from "../../components/title.vue";
import { setgoods, getgoods } from "../../common/SPXX";
import { getAccessToken } from "../../common/YYSLxx.js";
import { testUserMessage } from "../../common/testUser.js";
export default {
  components: {
    headerXX,
  },
  data() {
    return {
      title: "共享药房",
      id: 0,
      activeIndex: 0,
      activeId: "1",
      items: [],
      list: [],
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      imgshow: false,
      SPxx: {},
      categoryList: [],
      siteData: JSON.parse(localStorage.getItem("siteData")) || {},
      XXyz: {
        siteId: "",
        categoryId: 0,
        pageNumber: 1,
        pageSize: 10,
      },
    };
  },
  methods: {
    itemClick(item) {
      this.imgshow = true;
      item.goodManufacturer = this.categoryList[this.activeIndex].categoryName;
      let list = [];
      this.SPxx = item;
      list.push(this.SPxx);
      let li = encodeURIComponent(JSON.stringify(list).replace(/%/g, "%25"));
      // 把商品信息存储本地
      setgoods(li);
    },
    LQ() {
      this.imgshow = false;
      let decodedString = JSON.parse(
        decodeURIComponent(getgoods().replace(/%25/g, "%"))
      );
      let SPlist = [
        {
          id: this.SPxx.goodId,
          requestQty: 1,
        },
      ];
      const currentTimeStamp = moment().unix();
      const min = BigInt("1" + "0".repeat(18));
      const max = BigInt("1" + "0".repeat(19));
      const randomNum =
        min + BigInt(Math.floor(Math.random() * Number(max - min)));
      let goodMessage = decodedString;
      let itemXX = {
        SBBT: "共享药房",
        orderNumber: currentTimeStamp + randomNum.toString(), //预约编号
        siteId: this.siteData.id, // 服务点id
        orderProject: "共享药房", // 预约项目
        orderProjectType: "0", // 0:   1:  (区分健康自测类型与其他类型)
        orderCreationTime: moment().format("YYYY-MM-DD"), // 下单时间
        goodInfo: SPlist,
        estimateArrivalTime: "", // 服务时间
        estimateArrivalTimeTitle: "",
        estimateSumPrice: 0, // 预估费用
        orderSubType: "", // 预约类型
        serviceDescription: "", // 服务介绍
        orderLocation: "", // 预约地址(非空展示)
        serviceTip: "", // 温馨提示(非空展示)
        goodSumPrice: "", // 总价
        serviceTitleList: ["商品名称", "单价", "数量", "小计"], //服务标题
        goodList: [], //商品列表,
      };
      goodMessage.forEach((item) => {
        let obj = {
          goodId: item.goodId,
          goodName: item.goodName,
          servicePrice: item.goodPrice,
          serviceQty: item.goodQty,
          goodCountPrice: item.goodPrice * item.goodQty,
          serviceProjectName: "",
          remark: "",
          serviceMessage: "",
        };
        itemXX.goodList.push(obj);
      });
      getAccessToken(itemXX, "共享药房");
    },
    // 切换左侧分类
    onClickNav(index) {
      this.activeIndex = index;
      this.activeId = this.items[index].id;
      this.id = this.items[index].id;
      this.onRefresh();
    },
    // 下拉刷新
    onRefresh() {
      //   list.value = [];
      this.XXyz.pageNumber = 1;
      this.XXyz.pageSize = 10;
      this.finished = false;
      this.error = false;
      this.loading = true;
      this.refreshing = true;
      this.onLoad();
    },

    // 点击重试
    retryLoad() {
      this.error = false;
      this.loading = true;
      this.onLoad();
    },
    // 获取右边列表
    onLoad() {
      this.loading = true;
      if (this.error) return; // 如果当前是错误状态，不自动触发加载
      if (this.refreshing) {
        this.list = [];
      }
      // this.XXyz.companyId = this.arrayString.id
      this.XXyz.categoryId = this.activeId;

      getMedicineList(this.XXyz).then((res) => {
        if (res.resultMessage != "SUCCESS") {
          this.list = [];
          this.error = true; // 显示错误提示
          // loading.value = false;
        } else if (res.data.length == 0) {
          this.list = [];
          this.finished = true;
        } else {
          res.data = res.data.map((item) => {
            return {
              goodName: item.medName, // 名称
              goodId: item.id, // id
              goodImage: item.medImage, // 图片
              goodPrice: 0, // 价格
              goodDescription: item.medDescription, // 描述
              goodProducer: item.medProducer, // 生产厂家
              goodSumQty: item.medSum, // 总数量
              goodRemainQty: item.medRemain, // 剩余数量
              goodSiteId: item.siteId, // 站点id
              goodLocation: item.location, // 地址
              goodSpecifications: item.medSpecifications, // 规格
              btn: "领取",
              goodQty: 0,
              requestQty: 0,
            };
          });
          this.list = [...this.list, ...res.data];
          // list.value = res.data;
        }
        this.loading = false;
        // 判断是否已加载完所有数据
        if (this.list.length == res.pageNum) {
          this.finished = true;
        } else {
          this.XXyz.pageNumber++;
        }
        this.refreshing = false;
      });
    },
    // 获取左边列表
    getinformation() {
      //   arrayString.value = JSON.parse(decodeURIComponent(route.query.XX));
      getSiteCategoryList({
        siteId: this.siteData.id,
      }).then((res) => {
        if (res.resultCode == "1" && res.resultMessage == "SUCCESS") {
          this.items = res.data;
          console.log(this.items);
          this.categoryList = res.data;
          // 默认拿到第一个id
          this.id = this.items[this.activeIndex].id;
          this.items.forEach((item) => {
            item.text = item.categoryName;
          });
          this.onLoad();
        } else {
          Toast.fail("网络错误");
        }
      });
    },
  },
  mounted() {
    testUserMessage("共享药房").then((siteData) => {
      this.siteData = siteData[0];
      this.XXyz.siteId = siteData[0].id;
      this.getinformation();
    });
  },
};
</script>
<style lang="less" scoped>
.van-sidebar-item--select:before {
  background-color: rgb(2, 117, 113) !important;
}
@import "../../static/css/index.less";
@import "../../static/css/GYcSS.less";

.pull-refresh {
  background: #fff;
}

.error-tip {
  padding: 16px;
  color: #f56c6c;
  text-align: center;
}
.error-tip .van-icon {
  margin-right: 4px;
  vertical-align: middle;
}
</style>
